package cn.cht.service.impl;


import cn.cht.service.EmailService;
import org.apache.dubbo.config.annotation.Service;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import javax.annotation.Resource;
import javax.mail.internet.MimeMessage;
import java.util.concurrent.ThreadLocalRandom;


@Service
public class EmailServiceImpl implements EmailService {

    private static final Logger log = LoggerFactory.getLogger(EmailService.class);

    @Autowired
    private SimpleMailMessage registerEmailTemplate;
    @Resource
    private JavaMailSender mailSender;

    @Override
    public boolean send(String email, String code) {
        /**
         * 模拟可以失败
         */
        if (ThreadLocalRandom.current().nextBoolean() || true) {
            MimeMessage message = mailSender.createMimeMessage();
            MimeMessageHelper helper;
            try {
                helper = new MimeMessageHelper(message, true);//true indicates multipart message

                helper.setFrom(registerEmailTemplate.getFrom()); // <--- THIS IS IMPORTANT

                helper.setSubject(registerEmailTemplate.getSubject());
                helper.setTo(email);
                helper.setText("Thank to you register, you auth code <i>" + code + "</i>", true);//true indicates body is html

                mailSender.send(message);
                log.info("send code {} to email: {}", code, email);
                return true;
            } catch (Exception e) {
                log.error("send email error", e);
            }
        }
        return false;
    }
}
